from flask import Blueprint, request
from passlib.context import CryptContext
from cfg.model.UserModel import UserModel
from cfg.repo.custom_error import CustomError
from cfg.token import generate_token

# /auth 访问前缀
auth = Blueprint("auth", __name__, url_prefix="/auth")
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


# print(pwd_context.hash("e10adc3949ba59abbe56e057f20f883e"))


# 登录
@auth.route("/login", methods=['POST', 'GET'])
def login():
    """
    密码登录
    """
    username = request.form.get("username", type=str)
    old_password = request.form.get("password", type=str)
    if username is None or old_password is None:
        raise CustomError.user_pass_error()
    user = UserModel.query.filter(UserModel.username == username).first()
    if not user.password:
        raise CustomError.user_pass_error()
    # 验证密码
    is_valid = pwd_context.verify(old_password, user.password)
    if not is_valid:
        raise CustomError.user_pass_error()
    token = generate_token(user)
    return token


